package org.xiaoyu.feign.core.annotation;

import java.io.IOException;

import org.apache.zookeeper.WatchedEvent;
import org.apache.zookeeper.Watcher;
import org.apache.zookeeper.ZooKeeper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.support.BeanDefinitionBuilder;
import org.springframework.beans.factory.support.BeanDefinitionRegistry;
import org.springframework.context.EnvironmentAware;
import org.springframework.context.annotation.ImportBeanDefinitionRegistrar;
import org.springframework.core.annotation.AnnotationAttributes;
import org.springframework.core.env.Environment;
import org.springframework.core.type.AnnotationMetadata;
import org.springframework.util.StringUtils;
import org.xiaoyu.feign.core.FeignZookeeper;
/**
 * feign服务注册方法
 * @author zhangsaizz
 *
 */
public class FeignServiceRegister implements ImportBeanDefinitionRegistrar, EnvironmentAware{
	
	private static final Logger log = LoggerFactory.getLogger(FeignServiceRegister.class);
	
	private Environment environment;

	private static String serviceName;
	
	private static String serviceUrl;
	
	public static final String FEIGN_ZOOKEEPER_PATH = "/feignService";
	
	public static final String FEIGN_ZOOKEEPER = "feignZookeeper";
	

	@Override
	public void registerBeanDefinitions(AnnotationMetadata importingClassMetadata, BeanDefinitionRegistry registry) {
		AnnotationAttributes annoAttrs = AnnotationAttributes
				.fromMap(importingClassMetadata.getAnnotationAttributes(FeignService.class.getName()));
		serviceName = annoAttrs.getString("name");
		serviceUrl = annoAttrs.getString("url");
		FeignZookeeper.serviceName = serviceName;
		FeignZookeeper.serviceUrl = serviceUrl;
		if(!registry.containsBeanDefinition(FEIGN_ZOOKEEPER)) {
			String ip = environment.getProperty("feign.zookeeper.ip");
			if(StringUtils.isEmpty(ip)) {
				log.warn("[feign.zookeeper.ip] is default addresss : [127.0.0.1:2181]");
				ip = "127.0.0.1:2181";
			}
			BeanDefinitionBuilder builder = BeanDefinitionBuilder.genericBeanDefinition(FeignZookeeper.class);
			ZooKeeper zooKeeper = null;
			try {
				 zooKeeper = new ZooKeeper(ip, 1000, new Watcher() {	
					@Override
					public void process(WatchedEvent event) {
					}
				});
			} catch (IOException e) {
				e.printStackTrace();
			}
			builder.addConstructorArgValue(zooKeeper);
			registry.registerBeanDefinition(FEIGN_ZOOKEEPER, builder.getBeanDefinition());	
		}

	}

	@Override
	public void setEnvironment(Environment environment) {
		this.environment = environment;	
	}

}
